package com.frt.sygang.controller;/**
 * Created by 冯瑞涛 on 2022/9/19 14:46
 */

import com.frt.sygang.common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author 冯瑞涛
 * @version 1.0
 * @date 2022/9/19 14:46
 */
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${img.path}")
    private String basePath;

    /**
     * 文件上传方法
     * @param file 接收前端传输的数据
     * @return
     */
    @RequestMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //获取要上传的文件名
        String originalFilename = file.getOriginalFilename();
        //截取文件名后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //拼接为完整文件名
        String fileName= UUID.randomUUID().toString()+suffix;
        //创建文件类
        File filePath=new File(basePath);
        //若目录不存在则创建目录
        if (!filePath.exists()) {
            //创建目录
            filePath.mkdirs();
        }
        try {
            //上传文件到指定位置并为文件指定名称
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(fileName);
    }

    @RequestMapping("download")
    public void download(String name, HttpServletResponse response){
        try {
            response.setContentType("image/jpeg");
            FileInputStream inputStream=new FileInputStream(basePath+name);
            ServletOutputStream outputStream = response.getOutputStream();
            int length=0;
            byte[] bytes=new byte[1024];
            while ((length= inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,length);
                outputStream.flush();
            }
            inputStream.close();
            outputStream.close();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}
